package tgc.edu.yzy.web.administrator.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.yzy.custom.TreeDTO;
import tgc.edu.yzy.entity.Dapa;
import tgc.edu.yzy.entity.User;
import tgc.edu.yzy.service.DapaService;
import tgc.edu.yzy.service.UserService;

@Controller
@RequestMapping(value="administrator/department")
public class DapaController {
	@Autowired
	private DapaService dapaservice;
	@Autowired
	private UserService userservice;
	@RequestMapping(value="treelist")
	@ResponseBody
	private Object treelist(Integer id) {
		List<TreeDTO> trees=dapaservice.tree(id);
		return trees;
	}
	@RequestMapping(value="dapa")
	private String dapa() {
		return "administrator/department/depa"; 
	}
	//可推拽
		@RequestMapping(value="changeLevel")
		@ResponseBody
		private String changeLevel(Integer targetId,Integer sourceId,String point) {
			//得到目标对象
			Dapa treetargent=dapaservice.findById(targetId);
			//得到操作的对象
			Dapa treesource=dapaservice.findById(sourceId);
			//append top bottom
			if("append".equals(point)) {
				treesource.setParent(treetargent);
			}else {
				treesource.setParent(treetargent.getParent());
			} 
			dapaservice.save(treesource);
			return "ok";
		}
		@RequestMapping(value="treeadd")
		@ResponseBody
		private String treeadd(Integer parentId	,Dapa treeform) {
			if(treeform.getId()==null||treeform.getId()==0) {
				Dapa trees=new Dapa();
				trees.setParent(dapaservice.findById(parentId));
				trees.setName(treeform.getName());
				dapaservice.save(trees);
			}else {
				Dapa trees=dapaservice.findById(treeform.getId());
				trees.setName(treeform.getName());
				dapaservice.save(trees);
			}
			return "";
		}
		@RequestMapping(value="remove")
		@ResponseBody
		private boolean remove(Integer id) {
			Dapa dapass=dapaservice.findById(id);
			List<User> user = userservice.findByDapa(dapass);
			if(user.size()>0) {
				return false;
			}else {
				String nam="";
				String names = dapaservice.findByUser(id,nam);
				
				if(names==null||names=="") {
					//dapaservice.deleteByID(id);
					System.out.println(names);
					return true;
				}else {
					System.out.println(names);
					return false;
				}
			}
			
			//在不借助框架时，如何删除 递归删除节点
			//treeservice.treedelete(id);
		}
}
